from django_filters.rest_framework import FilterSet
from django_filters.filters import *
from .models import *
from apps.tms.models import TestPlan


class TestCaseFilterSet(FilterSet):
    name = CharFilter(lookup_expr="contains")
    start_time = DateFilter(
        field_name="create_time", lookup_expr="gte", label="开始日期"
    )
    end_time = DateFilter(field_name="create_time", lookup_expr="lt", label="结束日期")
    testplan = CharFilter(method="search_by_testplan", label="测试计划")

    def search_by_testplan(self, queryset, field, value):
        testcase_list = (
            TestPlan.objects.filter(id=value)
            .first()
            .testcases.values_list("id", flat=True)
        )
        return queryset.filter(id__in=testcase_list)

    class Meta:
        model = TestCase
        fields = [
            "name",
            "number",
            "product",
            "module",
            "reqs",
            "level",
            "type",
            "stage",
            "isauto",
            "testplan",
            "creator",
            "status",
            "start_time",
            "end_time",
        ]
